package org.sag.mallbf;

import java.io.DataOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Custom Header Spec
 *
 * Int32 Type + SubType (shop + roof/wall)
 * Int32 ShapeType
 * Int32 ObjId
 */
public class EGroup extends ObjGroup {

    Map<Integer, List<int[]>> value;

    public EGroup() {
        value = new HashMap<>();
        g = "";
    }

    @Override
    public void exportHeader(DataOutputStream dos, int version) throws Exception {
        String[] des = g.split("_");
        if (des.length < 4) {
            throw new Exception("Illegal Group Descriptor: " + g);
        }

        //Type
        if (des[0].equalsIgnoreCase("shop")) {
            Utils.putShort(dos, (short) 1, 1);
        } else {
            Utils.putShort(dos, (short) 0, 1);
        }

        //SubType
        if (des[2].equalsIgnoreCase("roof")) {
            Utils.putShort(dos, (short) 1, 1);
        } else if (des[2].equalsIgnoreCase("wall")) {
            Utils.putShort(dos, (short) 2, 1);
        } else  {
            Utils.putShort(dos, (short) 0, 1);
        }

        //ShapeType
        Utils.putInt(dos, Integer.parseInt(des[1]), 1);

        //ObjId
        Utils.putInt(dos, Integer.parseInt(des[3]), 1);
    }

    @Override
    public void exportContent(DataOutputStream dos) throws Exception {

        Utils.putInt(dos, value.keySet().size(), 1);

        for (Integer key : value.keySet()) {
            List<int[]> v = value.get(key);

            Utils.putInt(dos, v.size(), 1);
            Utils.putInt(dos, key, 1);
            Utils.putShort(dos, (short) -2, 1);
            Utils.putShort(dos, (short) 0, 1);

            for (int[] list : v) {
                Utils.putShort(dos, (short) list[0], 1);
                Utils.putShort(dos, (short) list[1], 1);
                Utils.putShort(dos, (short) list[2], 1);
            }

            if (v.size() % 2 != 0) {
                //spacer
                Utils.putShort(dos, (short) 0, 1);
            }
        }
    }
}
